package com.ruis.kotboot.common.base

import com.alibaba.fastjson.JSONPObject
import com.baomidou.kisso.SSOHelper
import com.baomidou.kisso.security.token.SSOToken
import com.ruis.kotboot.common.core.RuisException
import com.ruis.kotboot.common.util.HttpUtil
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.ExceptionHandler
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 控制器基类
 * 支持kisso
 * @author NorthLan at 2018/2/9
 */
abstract class RuisApiController {
    protected val logger = LoggerFactory.getLogger(this::class.java)

    protected fun getRequest(): HttpServletRequest {
        return HttpUtil.getRequest()
    }

    protected fun getResponse(): HttpServletResponse {
        return HttpUtil.getResponse()
    }

    protected fun getCurUserId(): Long {
        return getSSOToken().id.toLong()
    }

    protected fun getSSOToken(): SSOToken {
        return SSOHelper.attrToken(getRequest())
                ?: throw RuisException(0,"The user does not exist, please re-login.")
    }

    protected companion object {
        fun retMap():MutableMap<String,Any?>{return hashMapOf()}
        fun ok():ResponseEntity<Any?>{
            return ok(mapOf<String,Any?>())
        }
        fun ok(arg:Any?):ResponseEntity<Any?>{
            var ret=arg
            try {
                val callback=HttpUtil.getRequest().getParameter("callback")
                if (StringUtils.isNotBlank(callback))
                    ret= JSONPObject(callback).also {
                        it.addParameter(arg)
                    }
            }catch (e:Exception){}
            return ResponseEntity.ok(ret?: mapOf<String,Any?>())
        }
    }

    /**
     * 用于处理异常的
     * @return
     */
    @ExceptionHandler(RuisException::class)
    fun ruisException(e: RuisException): Any {
        logger.error("handler ruisException:",e)
        if (e.code>0)
            return ResponseEntity.status(510+e.code).body(e.message)
        else
            return ResponseEntity.status(510).body(e.message)
    }
    /**
     * 用于处理异常的
     * @return
     */
    @ExceptionHandler(Exception::class)
    fun exception(e: Exception): Any {
        logger.error("handler exception:",e)
        return ResponseEntity.status(500).body(e.message)
    }
}